<template>
  <a-modal
    :visible="true"
    :width="1000"
    :mask-closable="false"
    :on-before-ok="handleModalOk"
    @cancel="handleModalCancel"
  >
    <template #title>
      <span v-if="type === 'add'">新增</span>
      <span v-else>编辑</span>
    </template>
    <a-form ref="formRef" :model="formData" auto-label-width class="form">
      <a-row :gutter="16">
        <a-col
          v-for="(item, index) in columnData.filter(
            (v) =>
              (v.isAdd != false && typeof v.isAdd === 'boolean') ||
              v.isAdd === undefined
          )"
          :key="index"
          :span="item.addSpan || 12"
        >
          <a-form-item
            v-if="item.type === undefined || item.type === 'input'"
            :label="item.title + ':'"
            :field="item.dataIndex"
            :rules="[
              {
                required: !!item.required,
                message: `${item.title}` + '不能为空',
              },
            ]"
          >
            <a-input
              v-model="formData[item.dataIndex]"
              :max-length="item.maxLength"
              :disabled="!!item.disabled"
              :placeholder="'请输入' + item.title"
            />
          </a-form-item>

          <a-form-item
            v-else-if="item.type === 'inputTag'"
            :label="item.title + ':'"
            :field="item.dataIndex"
            :rules="[
              {
                required: !!item.required,
                message: `${item.title}` + '不能为空',
              },
            ]"
          >
            <a-input-tag
              v-model="formData[item.dataIndex]"
              :placeholder="'请输入' + item.title"
              :disabled="!!item.disabled"
              allow-clear
            />
          </a-form-item>

          <h3 class="titleLine" v-else-if="item.type === 'title'">{{
            item.title
          }}</h3>

          <a-form-item
            v-else-if="item.type === 'datePicker'"
            :label="item.title + ':'"
            :field="item.dataIndex"
            :rules="[
              {
                required: !!item.required,
                message: `${item.title}` + '不能为空',
              },
            ]"
          >
            <a-date-picker
              style="width: 100%"
              v-model="formData[item.dataIndex]"
              :disabled="!!item.disabled"
              :placeholder="'请输入' + item.title"
            />
          </a-form-item>

          <a-form-item
            v-else-if="item.type === 'monthPicker'"
            :label="item.title + ':'"
            :field="item.dataIndex"
            :rules="[
              {
                required: !!item.required,
                message: `${item.title}` + '不能为空',
              },
            ]"
          >
            <a-month-picker
              style="width: 100%"
              v-model="formData[item.dataIndex]"
              :disabled="!!item.disabled"
              :placeholder="'请输入' + item.title"
            />
          </a-form-item>

          <a-form-item
            v-else-if="item.type === 'yearPicker'"
            :label="item.title + ':'"
            :field="item.dataIndex"
            :rules="[
              {
                required: !!item.required,
                message: `${item.title}` + '不能为空',
              },
            ]"
          >
            <a-year-picker
              style="width: 100%"
              v-model="formData[item.dataIndex]"
              :disabled="!!item.disabled"
              :placeholder="'请输入' + item.title"
            />
          </a-form-item>

          <a-form-item
            v-else-if="item.type === 'quarterPicker'"
            :label="item.title + ':'"
            :field="item.dataIndex"
            :rules="[
              {
                required: !!item.required,
                message: `${item.title}` + '不能为空',
              },
            ]"
          >
            <a-quarter-picker
              v-model="formData[item.dataIndex]"
              :disabled="!!item.disabled"
              :placeholder="'请输入' + item.title"
            />
          </a-form-item>

          <a-form-item
            v-else-if="item.type === 'weekPicker'"
            :label="item.title + ':'"
            :field="item.dataIndex"
            :rules="[
              {
                required: !!item.required,
                message: `${item.title}` + '不能为空',
              },
            ]"
          >
            <a-week-picker
              v-model="formData[item.dataIndex]"
              :disabled="!!item.disabled"
              :placeholder="'请输入' + item.title"
            />
          </a-form-item>

          <a-form-item
            v-else-if="item.type === 'rangePicker'"
            :label="item.title + ':'"
            :field="item.dataIndex"
            :rules="[
              {
                required: !!item.required,
                message: `${item.title}` + '不能为空',
              },
            ]"
          >
            <a-range-picker
              :showTime="item.showTime"
              v-model="formData[item.dataIndex]"
              :mode="item.mode"
              :disabled="!!item.disabled"
            />
          </a-form-item>

          <a-form-item
            v-else-if="item.type === 'password'"
            :label="item.title + ':'"
            :field="item.dataIndex"
            :rules="[
              {
                required: !!item.required,
                message: `${item.title}` + '不能为空',
              },
            ]"
          >
            <a-input-password
              v-model="formData[item.dataIndex]"
              :max-length="item.maxLength"
              :disabled="!!item.disabled"
              :placeholder="'请输入' + item.title"
            />
          </a-form-item>

          <a-form-item
            v-else-if="item.type === 'file'"
            :label="item.title + ':'"
            :field="item.dataIndex"
            :rules="[
              {
                required: !!item.required,
                message: `${item.title}` + '不能为空',
              },
            ]"
          >
            <!-- :is-live-custom-handler="true"
              @parent-com-custom-handler="parentComCustomHandler" -->
            <Uploader
              v-model="formData[item.dataIndex]"
              ref="uploaderRef"
              :defaultFileList="formData[item.dataIndex]"
              :limit="item.limit"
              :listType="item.listType"
              :draggable="item.draggable"
              :isSlot="item.isSlot"
            >
              <div v-if="item.isSlot" v-html="item.slotContent"></div>
            </Uploader>
          </a-form-item>

          <a-form-item
            v-else-if="item.type === 'number'"
            :label="item.title + ':'"
            :field="item.dataIndex"
            :rules="[
              {
                required: !!item.required,
                message: `${item.title}` + '不能为空',
                validator: checkNumberValue,
              },
            ]"
          >
            <a-input-number
              v-model="formData[item.dataIndex]"
              model-event="input"
              :max="item.max || 999999999"
              :min="item.min || -999999999"
              :disabled="!!item.disabled"
              :placeholder="'请输入' + item.title"
            />
          </a-form-item>

          <a-form-item
            v-else-if="item.type === 'textarea'"
            :label="item.title + ':'"
            :field="item.dataIndex"
            :rules="[
              {
                required: !!item.required,
                message: `${item.title}` + '不能为空',
              },
            ]"
          >
            <a-textarea
              v-model="formData[item.dataIndex]"
              :max-length="item.maxLength"
              :placeholder="'请输入' + item.title"
              allow-clear
              :disabled="!!item.disabled"
            />
          </a-form-item>

          <a-form-item
            v-else-if="item.type === 'select'"
            :label="item.title + ':'"
            :field="item.dataIndex"
            :rules="[
              {
                required: !!item.required,
                message: `${item.title}` + '不能为空',
              },
            ]"
          >
            <a-select
              v-model="formData[item.dataIndex]"
              allow-clear
              :placeholder="'请选择' + item.title"
              :multiple="item.multiple"
            >
              <a-option
                v-for="(op, idx) in item.selectOptions"
                :key="idx"
                :label="op[item.options?.label || 'label']"
                :value="op[item.options?.value || 'value']"
              ></a-option>
            </a-select>
          </a-form-item>

          <a-form-item
            v-else-if="item.type === 'checkbox'"
            :label="item.title + ':'"
            :field="item.dataIndex"
            :rules="[
              {
                required: !!item.required,
                message: `${item.title}` + '不能为空',
              },
            ]"
          >
            <a-checkbox-group v-model="formData[item.dataIndex]">
              <a-checkbox
                v-for="(op, idx) in item.selectOptions"
                :key="idx"
                :value="op[item.options?.value || 'value']"
                :disabled="!!op.disabled"
                >{{ op[item.options?.label || 'label'] }}</a-checkbox
              >
            </a-checkbox-group>
          </a-form-item>

          <a-form-item
            v-else-if="item.type === 'radio'"
            :label="item.title + ':'"
            :field="item.dataIndex"
            :rules="[
              {
                required: !!item.required,
                message: `${item.title}` + '不能为空',
              },
            ]"
          >
            <a-radio-group v-model="formData[item.dataIndex]">
              <a-radio
                v-for="(op, idx) in item.selectOptions"
                :key="idx"
                :value="op[item.options?.value || 'value']"
                :disabled="!!op.disabled"
                >{{ op[item.options?.label || 'label'] }}</a-radio
              >
            </a-radio-group>
          </a-form-item>

          <a-form-item
            v-else-if="item.type === 'treeSelect'"
            :label="item.title + ':'"
            :field="item.dataIndex"
            :rules="[
              {
                required: !!item.required,
                message: `${item.title}` + '不能为空',
              },
            ]"
          >
            <a-tree-select
              v-model="formData[item.dataIndex]"
              :data="item.selectOptions"
              :placeholder="'请选择' + item.title"
              :field-names="item.options"
            ></a-tree-select>
          </a-form-item>

          <a-form-item
            v-else-if="item.type === 'chooseAddress'"
            :label="item.title + ':'"
            :field="item.dataIndex"
            :rules="[
              {
                required: !!item.required,
                message: `${item.title}` + '不能为空',
              },
            ]"
          >
            <div style="width: 100%">
              <div style="width: 100%; display: flex; align-items: center">
                <a-input
                  v-model="formData[item.dataIndex]"
                  :disabled="!!item.disabled || !formData[item.dataIndex]"
                  :placeholder="'请输入' + item.title"
                />
                <div style="width: 30px"></div>
                <a-button type="primary" @click="chooseAddress"
                  >选择地址</a-button
                >
              </div>
              <div style="margin-top: 10px; color: #666; font-size: 12px">
                经度:{{ formData.longitude || '-' }} &nbsp;&nbsp;&nbsp;纬度:{{
                  formData.latitude || '-'
                }}
              </div>
            </div>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <GdMap
      ref="txMap"
      v-model="isOpenMap"
      :lnglat="lnglat"
      @confrim-handler="confrimHandler"
    ></GdMap>
  </a-modal>
</template>

<script setup>
  import { ref, watch, toRefs, toRaw } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import GdMap from '@/templateDir/components/gd-map/index.vue';
  import Uploader from '@/templateDir/components/uploader/index.vue';
  import { addDataReq, updateDataReq, columnData } from './data';
  import _ from 'lodash'

  const checkNumberValue = (value, cb) => {
    if (!(typeof value === 'number' && !Number.isNaN(value))) {
      cb('请输入内容');
    }
  };

  const formData = ref({});
  const formRef = ref(null);

  // const parentComCustomHandler = (obj) => {
  //   console.log(obj);
  //   const f = new FormData();
  //   f.append('file', obj.file);
  //   deliverBatchLogFile(f)
  //     .then((res) => {
  //       formData.value.file = res?.data?.data?.list || [];
  //       formRef.value.validateField('file');
  //     })
  //     .catch(() => {});
  // };

  // const { proxy } = getCurrentInstance();
  const props = defineProps({
    show: Boolean,
    selectTrader: {
      type: Array,
      default: () => [],
    },
    type: {
      type: String,
      default: () => 'add',
    },
    data: {
      type: Object,
      default: () => ({}),
    },
  });

  const lnglat = ref([]);

  const txMap = ref(null);
  const uploaderRef = ref(null);

  const { type } = toRefs(props);
  const emits = defineEmits(['success', 'close']);

  // 弹窗关闭
  const handleModalCancel = () => {
    return emits && emits('close');
  };

  const isOpenMap = ref(false);

  const getMapDataIndex = () => {
    let key =
      columnData.value?.find?.((v) => v.type === 'chooseAddress')?.dataIndex ||
      '';
    return key;
  };

  const confrimHandler = (obj) => {
    let mapKey = getMapDataIndex();
    formData.value[mapKey] = obj.district + obj.address;
    formData.value.latitude = obj.location.lat;
    formData.value.longitude = obj.location.lng;
    // formData.value.provinceName = obj.province;

    const reg = /.+?(省|市|自治区|自治州|县|区)/g;
    const arr = obj.district.match(reg);
    formData.value.provinceName = arr[0]; // eslint-disable-line
    formData.value.provinceCode = obj.adcode.slice(0, 2);

    formData.value.cityName = arr.length > 2 ? arr[1] : arr[0];
    formData.value.cityCode = obj.adcode.slice(0, 4);

    formData.value.countyName = arr[arr.length - 1];
    formData.value.countyCode = obj.adcode;
    isOpenMap.value = false;
    formRef.value.validateField(mapKey);
  };

  // 弹窗确认
  const handleModalOk = async () => {
    
    let submitFormData = _.cloneDeep(toRaw(formData.value));
    const flag = await formRef.value.validate();
    // 图片需要拆解为逗号隔开的字符串
    columnData.value.forEach((v) => {
      if (
        v.type === 'file' &&
        submitFormData[v.dataIndex] &&
        submitFormData[v.dataIndex] instanceof Array
      ) {
        submitFormData[v.dataIndex] =
          submitFormData?.[v.dataIndex]?.join?.(',');
      } else if (v.type === 'rangePicker' && v?.interfaceKey?.length > 0) {
        submitFormData[v.interfaceKey[0]] = submitFormData?.[v.dataIndex]?.[0];
        submitFormData[v.interfaceKey[1]] = submitFormData?.[v.dataIndex]?.[1];
      } else if (v.type === 'monthPicker' && submitFormData[v.dataIndex]) {
        submitFormData[v.dataIndex] += '-00';
      } else if (v.type === 'checkbox' && submitFormData[v.dataIndex]) {
        submitFormData[v.dataIndex] = submitFormData[v.dataIndex]?.join?.(',');
      } else if (v.type === 'inputTag' && submitFormData[v.dataIndex]) {
        submitFormData[v.dataIndex] = submitFormData[v.dataIndex]?.join?.(',');
      }
    });

    if (!flag) {
      if (type.value === 'add') {
        const res = await addDataReq(submitFormData);
        if (res && res.code === 200) {
          Message.success('添加成功');
          if (emits) emits('success');
          return true;
        } else {
          return false;
        }
      } else {
        const res = await updateDataReq(submitFormData);
        if (res && res.code === 200) {
          Message.success('修改成功');
          if (emits) emits('success');
          return true;
        } else {
          return false;
        }
      }
    }
  };

  const chooseAddress = () => {
    isOpenMap.value = true;
  };

  watch(
    () => props.data,
    (n) => {
      /**
       * 这里统一设置默认值，或者一些对初始值的特殊处理
       */

      columnData.value.forEach((v) => {
        // 处理回填 number输入框回填失败的bug （前端传的number类型后端返回的有可能是String类型，导致<a-input-number/> 组件回填失败）
        if (v.type === 'number') {
          n[v.dataIndex] = Number(n[v.dataIndex]);
        } else if (v.type === 'rangePicker' && v?.interfaceKey?.length > 0) {
          let keys = v.interfaceKey;
          if (n[keys[0]] && n[keys[1]]) {
            n[v.dataIndex] = [n[keys[0]], n[keys[1]]];
          }
        }else if(v.type === 'inputTag' || v.type === 'checkbox') {
          n[v.dataIndex] = n[v.dataIndex]?.split(',')
        }
      });

      formData.value = n;
      if (props.type === 'add') {
        lnglat.value = [];
      } else if (n.longitude && n.latitude) {
        lnglat.value = [n.longitude, n.latitude];
      }
    },
    { deep: true, immediate: true }
  );
</script>

<style lang="less" scoped></style>
